package com.cloudxingkong.dianyinke.NewTeacher.Ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Adapter.TeacherLessonsAdapter;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.UploadUtils;
import com.cloudxingkong.dianyinke.NewTeacher.bean.TeacherLessons;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.Utils.MySwipeView;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 上传课程
 */
public class UploadWork extends AppCompatActivity implements  SwipeRefreshLayout.OnRefreshListener, TeacherLessonsAdapter.TeacherLessonsDataCallback {

    private ListView listview;
    private SharedPreferences sharedPreferences;
    private RelativeLayout uwClick;
    private List<TeacherLessons.ListBean> lessonList;
    private TeacherLessonsAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private String sessionID;
    private static final String getWork = ThisUri.SERVER_YUMING + ThisUri.THIS_MY_LESSION;

    private static final int GET_CODE=2333;
    private static final int RESULT_CODE=666;
    private TextView tvWork;
    private ProgressDialog progressDialog;
    private boolean isGetLessons=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_work);
        init();
        swipeRefreshLayout.setColorSchemeResources(R.color.colorGreen);
        sharedPreferences = getSharedPreferences("data_dyk", 0);
        sessionID = CookieHelper.getSessionID(sharedPreferences);
        String qryTavatar = sharedPreferences.getString("qryTavatar", "");
        adapter = new TeacherLessonsAdapter(listview,lessonList, this, this,qryTavatar);
        listview.setAdapter(adapter);

        swipeRefreshLayout.setOnRefreshListener(this);

        //设置自动刷新
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
            }
        });
        onRefresh();

        //进入上传课程
        uwClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UploadWork.this, UploadingWork.class);

                startActivityForResult(intent, GET_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==GET_CODE){
            if (resultCode==RESULT_CODE){
                swipeRefreshLayout.setRefreshing(true);
                onRefresh();
            }
        }
    }

    private void loadData() {
        //开启子线程获取数据
        new Thread() {
            @Override
            public void run() {
                super.run();
                UploadUtils.getData(getWork, sessionID, new UploadUtils.UploadCallback() {
                    @Override
                    public void onFinish(String state) {
                        Log.e("test","老师拉取课程 ："+state);

                        if (state != null && !state.equals("")) {
                            Message msg = handler.obtainMessage();
                            msg.what = 1;
                            msg.obj = state;
                            handler.sendMessage(msg);
                        }else{
                            swipeRefreshLayout.setRefreshing(false);
                            tvWork.setVisibility(View.VISIBLE);
                        }

                    }
                });
            }
        }.start();
    }


    private void loadLessonsData(String state) {
        Gson gson = new Gson();
        TeacherLessons lessons = gson.fromJson(state, TeacherLessons.class);

        if (lessons.getList() != null && lessons.getList().size() > 0) {
            tvWork.setVisibility(View.GONE);
            lessonList.addAll(lessons.getList());
            adapter.notifyDataSetInvalidated();

        }else{
            tvWork.setVisibility(View.VISIBLE);
        }
        swipeRefreshLayout.setRefreshing(false);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    String state = (String) msg.obj;
                    loadLessonsData(state);
                    break;
                case 2:
                    progressDialog.dismiss();
                    Toast.makeText(UploadWork.this, "删除成功！", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    progressDialog.dismiss();
                    Toast.makeText(UploadWork.this, "删除失败，请重试!", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    private void init() {
        tvWork = (TextView) findViewById(R.id.work_tv_msg);
        listview = (ListView) findViewById(R.id.listview_uploadwork);
        lessonList = new ArrayList<>();
        uwClick = (RelativeLayout) findViewById(R.id.uploadwork_click);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.uw_swiperefresh);
    }

    public void back(View view) {
        finish();
    }


    @Override
    public void onRefresh() {
        lessonList.clear();
        loadData();
    }

    @Override
    public void dataCallback(final int position, TextView del) {
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(UploadWork.this, UWDetail.class);
                intent.putExtra("coverPath", lessonList.get(position).getCoverpic());
                intent.putExtra("lessonID", lessonList.get(position).getId() + "");
                intent.putExtra("lessonTitle", lessonList.get(position).getTitle());
                intent.putExtra("lessonPrice", lessonList.get(position).getPrice() + "");
                intent.putExtra("lessonLabel", lessonList.get(position).getLabel());
                intent.putExtra("lessonAddr", lessonList.get(position).getAddr());
                intent.putExtra("lessonNote", lessonList.get(position).getNote());
                startActivity(intent);
            }
        });

        del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressDialog=ProgressDialog.show(UploadWork.this,null,"正在删除...",true,false);
                int id = lessonList.get(position).getId();
                Log.e("test","老师课程ID "+id);
                delLesson(id, v);
            }
        });

    }

    private void delLesson(int id, final View v) {

        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.DEL_LESSON);
        params.addHeader("cookie",sessionID);
        params.addBodyParameter("id", id + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                boolean isDel=false;
                Log.e("test", "老师删除课程结果 : " + result);
                HashMap<String, Object> fromLogin = LoginJsonUtils.getJsonFromLogin(result);
                Object success = fromLogin.get("success");
                isDel= (boolean) success;

                if (isDel==true){
                    //删除条目
                    String pos= (String) v.getTag();
                    ((MySwipeView) v.getParent()).quickClose();
                    lessonList.remove(Integer.parseInt(pos));
                    adapter.notifyDataSetChanged();
                    handler.sendEmptyMessage(2);
                }else{
                    handler.sendEmptyMessage(3);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
